<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #progressContainer {
            position: relative;
            margin: 20px 0;
            border: 1px solid #333333;
            width: 80%;
            height: 30px;
        }
        #progressStatus {
            width: 0%;
            height: 100%;
            background: #e3e3e3;
        }
        #progressText {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            text-align: center;
            line-height: 30px;
        }
    </style>
</head>
<body>

<input type="file" id="avatar">

<div id="progressContainer">
    <div id="progressStatus"></div>
    <div id="progressText">0%</div>
</div>

<script>
    let avatarElement = document.querySelector('#avatar');
    let progressContainerElement = document.querySelector('#progressContainer');
    let progressStatusElement = document.querySelector('#progressStatus');
    let progressTextElement = document.querySelector('#progressText');

    // 当 avatarElement 的值发生改变的时候（选择新的上传文件）
    avatarElement.onchange = function() {
        console.log('准备上传');

        let xhr = new XMLHttpRequest();

        xhr.open('post', '/avatar');

        xhr.onloadstart = function() {
            console.log('开始下载');
        }


        xhr.onload = function() {
            // console.log(this.responseText);
            let data = JSON.parse(this.responseText);
            // console.log(data)

            // let imgElement = new Image();
            // imgElement.src = data.url;
            // imgElement.style.width = '200px';
            // document.body.appendChild(imgElement);
        }

        xhr.upload.onloadstart = function() {
            console.log('开始上传了');
            progressStatusElement.style.width = '0%';
            progressTextElement.innerHTML = '0%';
        }

        let prevLoaded = 0;
        let prevTime = Date.now();

        xhr.upload.onprogress = function(e) {
            // 间隔(100ms左右)触发
            console.log('正在上传中...', e.loaded, e.total);

            // 计算两次loaded的差值
            let rateLoaded = e.loaded - prevLoaded;
            prevLoaded = e.loaded;

            let v = e.loaded / e.total * 100;

            progressStatusElement.style.width = v + '%';
            progressTextElement.innerHTML = v.toFixed(2) + '%' + ` ${rateLoaded} / s`;
        }

        xhr.upload.onload = function() {
            progressTextElement.innerHTML = '上传完成';
        }

        let fd = new FormData();
        // 不要使用 avatarElement.value，要上传的是文件数据本身，而不是文件名称
        fd.append('avatar', avatarElement.files[0]);
        xhr.send(fd);
    }
</script>

</body>
</html>
